#!/usr/bin/env python
# coding: utf-8

from google.appengine.ext import db

import data.model
import datetime
import module.utility
import module.user_manage
import logging

class GroupPurchase:
    @staticmethod
    def get_product(product_key):
        p = db.Model.get(product_key)
        if p == None:
            return -10
        return p
    
    @staticmethod
    def update_nondeposit_count(gp_key, userid, count):
        gp = db.Model.get(gp_key)
        if gp == None:
            return -10
        
        if userid != "admin":
            return -11
        gp.nondeposit_userid_count = gp.nondeposit_userid_count + count
        gp.put()
        
        return 0
    
    @staticmethod
    def check_launching(userid):
        retList = []
        
        q = db.GqlQuery("SELECT * FROM GroupPurchase WHERE product_key != NULL")
        items = q.fetch(100)
        
        for item in items:
            # Check triggered
            if item.trigger_userid == userid:
                gp = data.model.GPLaunching()
                gp.title = item.title
                gp.product_key = item.product_key
                logging.info("key:" + gp.product_key)
                retList.append(gp)
                
            # Check deposit
            if userid in item.deposit_userid_list:
                gp = data.model.GPLaunching()
                gp.title = item.title
                gp.product_key = item.product_key
                logging.info("key:" + item.product_key)
                retList.append(gp)
                
            # Check non deposit
            if userid in item.nondeposit_userid_list:
                gp = data.model.GPLaunching()
                gp.title = item.title
                gp.product_key = item.product_key
                logging.info("key:" + item.product_key)
                retList.append(gp)
                
        return retList
        
    
    @staticmethod
    def launch_gp(key, userid):
        # Get GroupPurchase Information
        gp = db.Model.get(key)
        if gp == None:
            return -10
        
        if userid != "admin":
            return -11
        
        # Create new Products entry
        p = data.model.Products()
        
        p.title = gp.title
        p.link = None
        p.time_start = datetime.datetime.now()
        p.time_end = p.time_start + datetime.timedelta(hours=24)
        p.price_original = gp.lprice
        p.price_now = int(gp.lprice * 0.8)
        p.sale_percent = 20
        p.photo_url = gp.photo_url
        p.area = None
        p.type = "g"
        p.category = None
        p.social_provider = "Social Curator"
        p.social_provider_code = 10000
        p.is_expired = 0
        keywords = []
        keywords.extend(module.utility.Utility.make_keywords(gp.title))
        p.keywords = keywords
        p.sell_list  = []
        p.sell_delta = 100000
        
        # Extra Information
        p.deposit_userid_count = gp.deposit_userid_count
        p.nondeposit_userid_count = gp.nondeposit_userid_count
        
        key = p.put()
        
        # Update GroupPurchase entry
        gp.product_key = str(key)
        gp.put()
        
        return 0
    
    @staticmethod
    def get_gp_list(start=0, limit=100):
        q = db.GqlQuery("SELECT * FROM GroupPurchase WHERE is_expired=0 ORDER BY deposit_userid_count ASC")
        return q.fetch(limit, start)
    
    # If success, return key in storage. If fail, return Error code
    @staticmethod
    def add_new_entry(title, trigger_userid, description, photo_url, lprice=0):
        if not module.utility.Utility.check_empty_parameter([title, trigger_userid, description]):
            return -2
        
        #TODO Check double entry
        
        today = datetime.datetime.today()

        gp = data.model.GroupPurchase()
        gp.title = title
        gp.trigger_userid = trigger_userid
        gp.description = description
        gp.lprice = lprice
        gp.photo_url = photo_url
        gp.time_start = today 
        gp.time_end = today + datetime.timedelta(days=7)
        gp.extend_count = 0
        gp.is_expired = 0
        gp.deposit_userid_count = 1
        gp.nondeposit_userid_count = 0
        
        # Launching group purchasing key
        gp.product_key = None
        
        key = gp.put()
        return key
    
    @staticmethod
    def get_entry(key):
        gp = db.Model.get(key)
        return gp
    
    @staticmethod
    def deposit_join(key, userid):
        gp = db.Model.get(key)
        # Check 
        if gp.trigger_userid == userid:
            return -6
        if userid in gp.deposit_userid_list:
            return -6
        
        # Check & update user's deposit
        ret = module.user_manage.UserManager.withdraw_deposit(userid, 1000)
        if ret < 0:
            return ret
        
        # Delete when already joined Nondeposit_join
        if userid in gp.nondeposit_userid_list:
            l = gp.nondeposit_userid_list
            l.remove(userid)
            gp.nondeposit_userid_list = l
            
        # Update group purchase item list
        userid_list = gp.deposit_userid_list
        userid_list.append(userid)
        gp.deposit_userid_list = userid_list
        gp.deposit_userid_count = len(userid_list)+1
        gp.put()
        
        # Update user information
        ret = module.user_manage.UserManager.add_dlist(userid, key)
        if ret < 0:
            return ret
        
        return 0
    
    @staticmethod
    def nondeposit_join(key, userid):
        gp = db.Model.get(key)
        # Check
        if gp.trigger_userid == userid:
            return -6
        if userid in gp.nondeposit_userid_list:
            return -6
        if userid in gp.deposit_userid_list:
            return -9
        
        userid_list = gp.nondeposit_userid_list
        userid_list.append(userid)
        gp.nondeposit_userid_list = userid_list
        gp.nondeposit_userid_count = len(userid_list)
        gp.put()
        
        # Update user information
        ret = module.user_manage.UserManager.add_nlist(userid, key)
        if ret < 0:
            return ret
        
        return 0
    
    @staticmethod
    def join_leave(key, userid):
        gp = db.Model.get(key)
        
        if userid in gp.deposit_userid_list:
            userid_list = gp.deposit_userid_list
            ret = module.user_manage.UserManager.add_deposit(userid, 1000)
            if ret < 0:
                return ret
            userid_list.remove(userid)
            gp.deposit_userid_list = userid_list
            gp.deposit_userid_count = len(userid_list)
            gp.put()
            
            # Update user information
            ret = module.user_manage.UserManager.del_dlist(userid, key)
            if ret < 0:
                return ret
            
            return 0
        elif userid in gp.nondeposit_userid_list:
            userid_list = gp.nondeposit_userid_list
           
            userid_list.remove(userid)
            gp.nondeposit_userid_list = userid_list
            gp.nondeposit_userid_count = len(userid_list)
            gp.put()
            
            # Update user information
            ret = module.user_manage.UserManager.del_nlist(userid, key)
            if ret < 0:
                return ret
            
            return 0
        else:
            return -7